<script lang="ts" setup>
import { onMounted, ref, watch, reactive, onBeforeUnmount } from 'vue'
import type { Ref } from 'vue'
import { useTianDiTu, useDraw } from '@/hooks/map'
import { Feature, Map } from 'ol'
import type { Type as DrawType } from 'ol/geom/Geometry'
import { useMessage } from 'naive-ui'
import { Point, SimpleGeometry } from 'ol/geom'
import VectorLayer from 'ol/layer/Vector'
import VectorSource from 'ol/source/Vector'
import { Style, Circle as CircleStyle } from 'ol/style'
import Fill from 'ol/style/Fill'
import Stroke from 'ol/style/Stroke'
const message = useMessage()

const xc = [114.86933826966052, 33.46835219138212]



const drawerShow = ref<boolean>(false)
const pointData = reactive<{
    title: string,
    icon: string,
}>({
    title: '',
    icon: ''

})
const submitPoint = () => {

}


const { simpleMap } = useTianDiTu()
const map = ref<Map | null>(null)
const drawtype = ref<'None' | DrawType>('None')
const drawtypelist = ref<{
    label: string, value: 'None' | DrawType
}[]>([
    { label: '无', value: 'None' },
    { label: '点', value: 'Point' },
    { label: '线', value: 'LineString' },
    { label: '圆', value: 'Circle' },
    { label: '面', value: 'Polygon' }
])

const { end, start, clear, show, hide } = useDraw({
    name: 'test_draw',
    map: map as Ref<Map>,
    drawType: drawtype,
    drawend(event, drawLayer) {
        const geometry = event.feature.getGeometry() as SimpleGeometry
        const coordinates = geometry.getCoordinates()
        if (geometry instanceof Point) {
            const p = (geometry as Point).getCoordinates()
            console.log('point', p);
        }


        // const id = event.feature.getId()
        // const ff = drawLayer.getSource()?.getFeatureById(id as string)
        event.feature.setProperties({ name: '456' })
        // message.success(JSON.stringify(event.feature))
        console.log('绘制', { event, drawLayer, geometry }, event.feature, drawLayer.getSource()?.getFeatures());
    }
})

onMounted(() => {
    map.value = simpleMap('draw_map')
    const test = new VectorLayer({
        source: new VectorSource({
            wrapX: false
        }),
        properties: {
            name: "TEST_POINT"
        }
    })
    map.value.addLayer(test)
    const pointFeature = new Feature({
        geometry: new Point([xc[0], xc[1]]), // 使用经纬度坐标创建点要素
        name: '散点1' // 添加其他属性到要素中
        ,title: "项城市"
    })
    pointFeature.setStyle(new Style({
        image: new CircleStyle({
            radius: 6, // 散点的半径
            fill: new Fill({
                color: 'red' // 散点的填充颜色
            }),
            stroke: new Stroke({
                color: 'white', // 散点的边框颜色
                width: 2 // 散点的边框宽度
            })
        })
    }))
    test.getSource()?.addFeature(pointFeature)
    map.value.on('click', (event) => {
        map.forEachFeatureAtPixel(event.pixel, (feature, layer, geometry) => {
            console.log('click', { feature, layer, geometry });
            message.success(`${feature.get("title")} 的坐标： ${(geometry as SimpleGeometry).getCoordinates()}`)

        },{
            layerFilter: (layer) => layer.get("name") === "draw_test_draw"
        })
    })
    window.$app.$map = map
})
onBeforeUnmount(() => {
    window.$app.$map = null
})


watch(drawtype, () => {
    if (drawtype.value === 'None') {
        end()
    } else {
        start()
    }
})

</script>
<template>
    <div id="containder">
        <div id="draw_map" class="map-containder"></div>
        <div class="control-list">
            <div class="select-label">
                <label for="drawtype">绘制类型：</label>
                <n-select id="drawtype" v-model:value="drawtype" filterable placeholder="选择绘制类型" :options="drawtypelist" />
            </div>
            <n-space class="btn-groups" align="center" justify="center">
                <n-button type="primary" @click="clear">
                    清空
                </n-button>
                <n-button type="primary" @click="show">
                    显示图层
                </n-button>
                <n-button type="primary" @click="hide">
                    隐藏图层
                </n-button>
            </n-space>
        </div>

        <n-drawer v-model:show="drawerShow" :width="502" placement="left" :mask-closable="false">
            <n-drawer-content title="斯通纳" closable>
                <n-form ref="formRef" inline :label-width="80" :model="pointData" size="large">
                    <n-form-item label="姓名" path="title">
                        <n-input v-model:value="pointData.title" placeholder="输入姓名" />
                    </n-form-item>
                    <n-form-item>
                        <n-button attr-type="button" @click="submitPoint">
                            提交
                        </n-button>
                    </n-form-item>
                </n-form>
            </n-drawer-content>
        </n-drawer>
    </div>
</template>
<style scoped>
.map-containder {
    position: relative;
    height: calc(100vh - 110px);
    width: 100%;
}

.control-list {
    position: absolute;
    right: 100px;
    bottom: 200px;
    height: 20vh;
    padding: 5px;
    width: 270px;
    background-color: rgba(138, 238, 238, 0.336);
    border-radius: 5px;
}

.btn-groups {
    margin-top: 5px;
}

.select-label {
    display: flex;
    justify-content: center;
}

.select-label>label {
    width: 120px;
    line-height: 34px;
}
</style>